<?php

class Aliyun_sms_service extends MY_Service {

    public function __construct() {
        parent::__construct();

        $this->load->model("api_log_model");

        $this->_config = config_item("aliyun_sms");
    }

    public function sendSms($signName, $phoneNumbers, $templateCode, $templateParam) {

        $param = [
            'Action' => 'SendSms',
            'Version' => '2017-05-25',
            'RegionId' => 'cn-hangzhou',
            'PhoneNumbers' => $phoneNumbers,
            'SignName' => $signName,
            'TemplateCode' => $templateCode,
            'TemplateParam' => $templateParam,
        ];

        //log_message('debug', "运满满调车->发布货源(请求数据)=>" . $source . "|" . jsonEncode($paramTmp));

        $result = $this->postApi($this->_config["dysmsapi_url"], $param, "发送短信", "POST");

        $truename = "";
        $sex = "";
        $id_card = "";

        if ($result["status_code"] == 1) {
            
        } else {
            
        }

        return $result;
    }

    public function postApi($url, $params, $item, $method = "GET") {

        $utc_time = strtotime("-8 hours");

        $paramsTmp = [
            "Format" => "JSON",
            "AccessKeyId" => $this->_config["accessKeyId"],
            "SignatureNonce" => uniqid(),
            "Timestamp" => date("Y-m-d", $utc_time) . "T" . date("H:i:s", $utc_time) . "Z",
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureVersion" => "1.0",
        ];
        $params = array_merge($paramsTmp, $params);

        $str = "";
        ksort($params);
        foreach ($params as $k => $v) {
            $str .= "&" . $k . "=" . urlencode($v);
        }
        $str = trim($str, "&");

        $Signature = $this->getSignature($method . "&%2F&" . urlencode($str), $this->_config["accessKeySecret"] . "&");

        $str .= "&Signature=" . urlencode($Signature);

        $params["Signature"] = $Signature;

        if ($method == "GET") {
            $url = $url . "/?" . $str;
        }

        $request_data = [
            "url" => $url,
                //"params" => $params,
        ];
        if ($method == "POST") {
            $request_data["params"] = $params;
        }

        log_message('error', "阿里云->" . $item . "(发送数据)=>" . jsonEncode($request_data));

        //$params = jsonEncode($params);

        $header = ['Content-Type:application/x-www-form-urlencoded'];

        //if (isset($this->_config["ocr"]["is_kaitong"]) && $this->_config["ocr"]["is_kaitong"] == 1) {

        $rs = $this->clientCurl($url, $params, $header, $method);

        //print_r($rs);
        $return_data = $rs["data"];

        $status_code = 0;
        $msg = "失败";
        $data = [];
        $return_code = "";

        if ($rs["code"] == 200) {
            $sys_data = jsonDecode($rs["data"]);
            if (isset($sys_data) && !empty($sys_data)) {
                if ($sys_data["Code"] == "OK") {
                    $status_code = 1;
                    $msg = "";
                    $data = $rs["data"];
                } else {
                    $msg = $sys_data["Message"] . "(" . $sys_data["Code"] . ")";
                }
            } else {
                $msg = "返回数据异常";
            }
        } else {
            $msg = "接口请求异常";
        }

        //增加日志
        $this->api_log_model->addLog(1, $item, $request_data, $return_data);

        log_message('error', "阿里云->" . $item . "(返回数据)=>" . (is_array($return_data) ? jsonEncode($return_data) : $return_data));

        return [
            "status_code" => $status_code,
            "msg" => $msg,
            "data" => $data,
            "return_code" => $return_code,
        ];
//        } else {
//            return [
//                "status_code" => 0,
//                "msg" => "未开通ocr",
//                "data" => [],
//                "return_code" => "",
//            ];
//        }
    }

    public function clientCurl($url, $postData = [], $header = [], $method = "GET") {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        /*         * 配置返回信息* */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //获取的信息以文件流的形式返回，不直接输出
        curl_setopt($ch, CURLOPT_HEADER, 0); //不返回header部分
        /*         * 配置超时* */
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //连接前等待时间,0不等待
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //连接后等待时间,0不等待
        /*         * 配置页面重定向* */
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//跟踪爬取重定向页面
        //curl_setopt($ch, CURLOPT_MAXREDIRS, 10);//指定最多的HTTP重定向的数量
        //curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        /*         * 配置HEADER* */
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        //curl_setopt($ch, CURLOPT_ENCODING, ""); // Accept-Encoding编码，支持"identity"/"deflate"/"gzip",空支持所有编码
        if (strpos(strtolower($url), 'https') !== false) {
            /*             * 禁止证书验证防止curl输出空白* */
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //禁止 cURL 验证对等证书
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //是否检测服务器的域名与证书上的是否一致
        }
        /*         * 配置POST* */
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1); //支持post提交数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        }


        $code = 200; //执行成功
        $result_data = curl_exec($ch);
        if (curl_errno($ch)) {
            $code = 400; //执行异常
            $result_data = curl_error($ch);
        }
        curl_close($ch);

        return ['code' => $code, 'data' => $result_data];
    }

    function getSignature($str, $key) {
        $signature = "";
        if (function_exists('hash_hmac')) {
            $signature = base64_encode(hash_hmac("sha1", $str, $key, true));
        } else {
            $blocksize = 64;
            $hashfunc = 'sha1';
            if (strlen($key) > $blocksize) {
                $key = pack('H*', $hashfunc($key));
            }
            $key = str_pad($key, $blocksize, chr(0x00));
            $ipad = str_repeat(chr(0x36), $blocksize);
            $opad = str_repeat(chr(0x5c), $blocksize);
            $hmac = pack(
                    'H*', $hashfunc(
                            ($key ^ $opad) . pack(
                                    'H*', $hashfunc(
                                            ($key ^ $ipad) . $str))
                    )
            );
            $signature = base64_encode($hmac);
        }
        return $signature;
    }

}
